//#include "stdafx.h"
#include "base_buffer.h"
#include <stdio.h>
#include <stdlib.h>

//////////////////////////////////////////////////////
// class buffer_t
//

buffer_t::buffer_t( uint32 grow ) : m_length(0),m_size(0), m_grow(grow)
{
	m_buffer = NULL;
}
buffer_t::buffer_t( uint32 size, uint32 grow ) : m_length(0), m_size(0), m_grow(grow)
{
	m_buffer = new uchar[size+1];
	if( m_buffer )
	{
		m_size = size;
	}
}

buffer_t::buffer_t( const void* buf, uint32 len ) : m_length(0), m_size(0)
{
	m_buffer = new uchar[len+1];
	if( m_buffer )
	{
		m_size = len;
		write( buf, len );
	}
}

buffer_t::~buffer_t()
{
	clear();
}

void buffer_t::reset( uint32 size, uint32 grow )
{
	clear();
	m_buffer = new uchar[size];
	if( !m_buffer )
	{
		return;
	}
	m_length	= 0;
	m_size		= size;
	m_grow      = grow;
}

void buffer_t::clear()
{
	if( m_buffer != NULL )
	{
		delete []m_buffer;
		m_buffer = NULL;
	}
	m_length	= 0;
	m_size		= 0;
}

void buffer_t::resize( uint32 size )
{
//	m_buffer.resize(size);
	uchar * temp = new uchar[size+1];
	if( !temp )
	{
		return;
	}
	
	if ( size < m_length ) 
	{
		memcpy( temp, m_buffer, size );
		m_length = size;
	}
	else
	{
		memcpy( temp, m_buffer, m_length );
	}
	delete []m_buffer;
	m_buffer = temp;
	m_size = size;
}

void buffer_t::write( const void* buf, uint32 len )
{
	if( (m_size - m_length) < len )
	{
		resize( m_size + len + m_grow );
	}

	if( !m_buffer || ( m_size - m_length ) < len )
	{
		return;
	}
	
	memcpy( m_buffer + m_length, buf, len );
	m_length += len;
}

void  buffer_t::reserve( uint32 bytes )
{
	if( m_size < bytes )
	{
		resize( bytes );
	}
	m_length = bytes;
}
void buffer_t::descard( uint32 bytes )
{
	if( bytes <= 0 ) 
	{
		return;
	}
	
	if( m_length >= bytes )
	{
		m_length -= bytes;
		memmove( m_buffer, m_buffer + bytes, m_length );
	}
	else
	{
		m_length = 0;
	}
}
